from django.conf import settings

import facebook

from auth import models

class FacebookConnectMiddleware:
  """Middleware for automatically handling login via Facebook Connect."""
  def process_request(self, request):
    """Check for a Facebook Connect cookie. If it doesn't exist, we set
    request.user to None. If it does exist, we look up the associated
    uid. If there is no user in our db with that uid, we create a new 
    user object.
    """
    assert(
      hasattr(request, 'session'), 
      "The Facebook Connect middleware requires session middleware to be "
      "installed. Edit your MIDDLEWARE_CLASSES setting to insert "
      "'django.contrib.sessions.middleware.SessionMiddleware'."
    )
    request.__class__.user = None
      
    # No user in the session, look for a Facebook cookie
    cookie = facebook.get_user_from_cookie(
      request.COOKIES,
      settings.FACEBOOK_APP_ID,
      settings.FACEBOOK_APP_SECRET)
    if cookie:
      try:
        request.user = models.User.objects.get(pk=cookie['uid'])
      except models.User.DoesNotExist:
        request.user = models.User(fbid=cookie['uid'])
        request.user = request.user.refresh(cookie['access_token'])
      request.user.login(request)
    else:
      models.User.logout(request)
